﻿namespace Probel.Ldoc.Shell.Tools
{
    /*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
    */
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;

    using log4net.Config;

    class Log4netConfigurator
    {
        #region Fields

        private string FILE = "log4net.xml";

        #endregion Fields

        #region Properties

        private string DirectoryPath
        {
            get
            {
                return Environment.ExpandEnvironmentVariables(@"%appdata%\Probel\nDoctor Light\");
            }
        }

        private string FileName
        {
            get
            {
                return Path.Combine(DirectoryPath, FILE);
            }
        }

        #endregion Properties

        #region Methods

        public void Configure()
        {
            if (!Directory.Exists(DirectoryPath)) { Directory.CreateDirectory(DirectoryPath); }
            if (!File.Exists(FileName)) { CreateFile(); }

            // Configure log4net. If you want to use the attached console, you
            // should configure Log4Net after the console is hooked
            XmlConfigurator.Configure(new FileInfo(FileName));
        }

        private void CreateFile()
        {
            var config = this.GetEmbeddedConfiguration();

            // Create a file to write to.
            using (var sw = File.CreateText(FileName))
            {
                sw.Write(config);
            }
        }

        private string GetEmbeddedConfiguration()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "Probel.Ldoc.Shell.log4net.xml";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }

        #endregion Methods
    }
}